import 'package:cbec_app/components/base/base_customize_segmented_control.dart';
import 'package:cbec_app/components/base/base_image.dart';
import 'package:cbec_app/components/base/base_interactive.dart';
import 'package:cbec_app/components/common/common_style.dart';
import 'package:cbec_app/components/common/count_down_timer.dart';
import 'package:cbec_app/components/common/not_found.dart';
import 'package:cbec_app/pages/goods/controller/discount_goods_ctr.dart';
import 'package:cbec_app/pages/goods/entity/activity_item_entity.dart';
import 'package:cbec_app/routes/routes.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../binding/goods_detail_binding.dart';
import 'goods_detail_page.dart';

//特价商品列表
class DiscountGoodsList extends GetView<DiscountGoodsController> {
  const DiscountGoodsList({super.key});

  List<Widget> _createItemWidgets() {
    final DiscountGoodsController controller = Get.find<DiscountGoodsController>();
    List<Widget> widgetArr = [];
    for (int i = 0; i < controller.itemList.length; i++) {
      ActivityItemEntity item = controller.itemList[i];
      int selectIndex = controller.selected;
      if (i == 0) {
        widgetArr.add(
          Container(
            padding: const EdgeInsets.only(left: 5, top: 5, bottom: 0, right: 5),
            child: Column(
              // mainAxisAlignment: MainAxisAlignment.center,
              children: [
                CountDownTimer(
                  timeStamp: DateTime.parse(item.endtime ?? '').millisecondsSinceEpoch,
                  timeStyle: TimeStyle.hhmmss,
                  countDownStyle: CountDownStyle.box,
                  boxBackgroundColor: Tools.fromHex("#000000"),
                  colonColor: Tools.fromHex("#000000"),
                  style: setTextStyle(
                    12,
                    FontWeight.w400,
                    Tools.fromHex('#FFFFFF'),
                  ),
                  callback: () {},
                ),
                const SizedBox(
                  height: 5,
                ),
                Text(
                  '正在抢购',
                  style: TextStyle(
                    color: selectIndex == i ? Tools.fromHex('#F83F2D') : Tools.fromHex('#FFFFFF'),
                  ),
                ),
              ],
            ),
          ),
        );
      } else {
        widgetArr.add(
          Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                item.begintime ?? '',
                style: TextStyle(
                  color: selectIndex == i ? Tools.fromHex('#F83F2D') : Tools.fromHex('#FFFFFF'),
                ),
              ),
              const SizedBox(
                height: 3,
              ),
              Text(
                '即将开始',
                style: TextStyle(color: selectIndex == i ? Tools.fromHex('#F83F2D') : Tools.fromHex('#FFFFFF'), fontWeight: FontWeight.w500, fontSize: 12),
              ),
            ],
          ),
        );
      }
    }
    return widgetArr;
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<DiscountGoodsController>(builder: (controller) {
      return Scaffold(
        extendBodyBehindAppBar: true,
        appBar: AppBar(
          backgroundColor: Colors.transparent,
          leading: IconButton(
            icon: const Icon(
              Icons.arrow_back,
              color: Colors.black,
            ),
            onPressed: () {
              Navigator.pop(context);
            },
          ),
        ),
        backgroundColor: Tools.fromHex("#F3F5F7"),
        body: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            //自适应高度的图片
            SizedBox(
              width: double.infinity,
              child: Image.asset("assets/images/tejia.png", fit: BoxFit.fitWidth),
            ),

            SizedBox(
              height: 60,
              child: BaseCustomizeSegmentedControl(
                  items: _createItemWidgets(),
                  selectedIndex: controller.selected,
                  onChanged: (index) {
                    controller.change(index);
                  }),
            ),
            //商品列表
            Expanded(
              child: controller.goodsList.isNotEmpty
                  ? Tools.getPullRefresh(
                      enablePullDown: true,
                      enablePullUp: true,
                      refreshController: controller.baseRefreshCtr,
                      onRefresh: controller.onPageRefresh,
                      onLoading: controller.onPageLoading,
                      child: ListView.builder(
                        controller: controller.scrollController,
                        padding: EdgeInsets.zero, // 移除默认的内边距
                        itemCount: controller.goodsList.length,
                        itemBuilder: (context, index) {
                          Map item = controller.goodsList[index];
                          return activityGoodItem(item);
                        },
                      ))
                  : const NotFound(),
            ),
          ],
        ),
      );
    });
  }

  Widget activityGoodItem(Map item) {
    return BaseInteractive(
      onClick: () {
        final id = item['goodsId'];
        Get.to(
          () => GoodsDetailPage(flag: id), // 使用函数懒加载页面实例
          routeName: '${Routes.goodsDetail}?unique=${DateTime.now().millisecondsSinceEpoch}',
          arguments: {"id": id}, // 传递其它参数
          binding: GoodsDetailBinding(flag: id), // 将 tag 参数传递给绑定类
        );
      },
      childWidget: Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(8.0),
        ),
        padding: const EdgeInsets.all(8.0),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            ClipRRect(
              borderRadius: BorderRadius.circular(8.0),
              child: BaseImage(
                url: item['mainImage'],
                height: 116.h,
                width: 116.w,
              ),
            ),
            SizedBox(width: 10.w),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    item['commodityName'],
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis, // 超出部分显示省略号
                    style: TextStyle(fontSize: 14.0, color: Tools.fromHex('#333333')),
                  ),
                  SizedBox(height: 8.h), // 添加一些间距
                  Container(
                    decoration: BoxDecoration(
                      color: Tools.fromHex('#FFEEEE'),
                      borderRadius: BorderRadius.circular(5.0),
                    ),
                    padding: const EdgeInsets.all(5),
                    child: Text(
                      item['commodityType'] == 0
                          ? "一般贸易"
                          : item['commodityType'] == 1
                              ? "保税"
                              : item['commodityType'] == 2
                                  ? "海外直邮"
                                  : "",
                      style: setTextStyle(10, FontWeight.w300, Tools.fromHex("#F83F2D")),
                    ),
                  ),
                  SizedBox(height: 8.h), // 添加一些间距
                  activityGoodItemBottom(item)
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget activityGoodItemBottom(Map item) {
    return SizedBox(
      height: 50.0,
      child: Stack(
        alignment: Alignment.center,
        children: [
          Row(
            children: [
              Expanded(
                child: Container(
                  decoration: BoxDecoration(
                    color: Tools.fromHex('#FCEDE4'),
                    borderRadius: const BorderRadius.only(
                      topLeft: Radius.circular(8.0),
                      bottomLeft: Radius.circular(8.0),
                    ),
                  ),
                  height: 50.0,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Padding(
                        padding: const EdgeInsets.only(left: 10),
                        child: Text(
                          '¥${item['price'].toString()}',
                          style: TextStyle(
                            fontSize: 16.0,
                            color: Tools.fromHex('#95511B'),
                            decoration: TextDecoration.lineThrough,
                            decorationColor: Tools.fromHex('#95511B'),
                          ),
                        ),
                      ),
                      Padding(
                        padding: const EdgeInsets.only(left: 10),
                        child: Text('剩余${item['storage'] > 50 ? '50+' : item['storage']}', style: TextStyle(color: Tools.fromHex('#95511B'), fontSize: 14)),
                      ),
                    ],
                  ),
                ),
              ),
              Expanded(
                child: Container(
                    decoration: BoxDecoration(
                      color: Tools.fromHex('#F83F2D'),
                      borderRadius: const BorderRadius.only(
                        topRight: Radius.circular(25.0),
                        bottomRight: Radius.circular(25.0),
                      ),
                    ),
                    height: 50.0,
                    child: Column(
                      children: [
                        Text('¥${item['specialPrice'].toString()}', style: TextStyle(color: Tools.fromHex('#FFFFFF'), fontSize: 16)),
                        Text('特卖价', style: TextStyle(color: Tools.fromHex('#FFFFFF'), fontSize: 14)),
                      ],
                    )),
              ),
            ],
          ),
          Positioned(
            child: SizedBox(
              width: 16.0,
              height: 50.0,
              child: BaseImage(
                url: 'shandian.png',
                height: 50.0,
                width: 16.0,
              ),
            ),
          ),
        ],
      ),
    );
  }
}
